from qcloud_cos import CosConfig, CosS3Client
from qcloud_cos.cos_exception import CosServiceError, CosClientError
from typing import Optional, Dict, Any
import uuid
import time
from .config import tencent_settings

class TencentCOSService:
    """腾讯云COS对象存储服务"""
    
    def __init__(self):
        self.client = self._create_client()
        self.bucket = tencent_settings.cos_bucket
        self.region = tencent_settings.cos_region
    
    def _create_client(self) -> CosS3Client:
        """创建COS客户端"""
        config = CosConfig(
            Region=tencent_settings.cos_region,
            SecretId=tencent_settings.secret_id,
            SecretKey=tencent_settings.secret_key
        )
        return CosS3Client(config)
    
    def upload_image(self, image_data: bytes, file_extension: str = 'jpg', 
                    folder: str = 'images') -> Dict[str, Any]:
        """上传图片到COS"""
        try:
            # 生成唯一文件名
            file_name = f"{uuid.uuid4().hex}_{int(time.time())}.{file_extension}"
            key = f"{folder}/{file_name}"
            
            # 上传文件
            response = self.client.put_object(
                Bucket=self.bucket,
                Body=image_data,
                Key=key,
                ContentType=f'image/{file_extension}'
            )
            
            # 构建访问URL
            url = f"https://{self.bucket}.cos.{self.region}.myqcloud.com/{key}"
            
            return {
                'success': True,
                'url': url,
                'key': key,
                'etag': response['ETag'],
                'file_name': file_name
            }
            
        except (CosServiceError, CosClientError) as e:
            raise Exception(f"COS上传失败: {e}")
    
    def delete_image(self, key: str) -> bool:
        """删除COS中的图片"""
        try:
            self.client.delete_object(
                Bucket=self.bucket,
                Key=key
            )
            return True
        except (CosServiceError, CosClientError) as e:
            raise Exception(f"COS删除失败: {e}")